package com.hardson.toolkit.swing;

import java.awt.Dialog;
import java.awt.Frame;
import java.awt.Window;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;

import javax.swing.JDialog;
import javax.swing.WindowConstants;

import com.hardson.toolkit.swing.datepicker.IAutoHide;

import lombok.Getter;
import lombok.Setter;

public class AutoHideDialog extends JDialog implements IAutoHide {

	private static final long serialVersionUID = 1L;

	@Getter
	@Setter
	private boolean autoDispose;

	@Getter
	@Setter
	private boolean windowListenerActive = true;

	public AutoHideDialog(final Window window, final String title,
			final ModalityType modalityType) {
		super(window, title, modalityType);
		this.initComp();
	}

	public AutoHideDialog(final Frame owner, final String title, final boolean modal) {
		super(owner, title, modal);
		this.initComp();
	}

	public AutoHideDialog(final Dialog owner, final String title, final boolean modal) {
		super(owner, title, modal);
		this.initComp();
	}

	private void initComp() {
		// this.setUndecorated(false);
		this.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		// ((JPanel)this.getContentPane()).setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
		// 如果非模态，添加窗口监听，窗口不活动时关闭
		WindowListener windowListener = new WindowAdapter() {
			@Override
			public void windowDeactivated(final WindowEvent e) {
				AutoHideDialog.this.windowDeactivated(e);
			}
		};
		this.addWindowListener(windowListener);
		// 非模态下自动关闭对话框
		this.autoDispose = !this.isModal();
	}

	private void windowDeactivated(final WindowEvent e) {
		if (this.windowListenerActive && this.autoDispose) {
			this.dispose();
		}
	}

	/**
	 * 添加ESCAPE监听，按下ESCAPE键后退出
	 */
	// @Override
	/*
	 * protected JRootPane createRootPane() { KeyStroke stroke =
	 * KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0); JRootPane rootPane =
	 * super.createRootPane(); rootPane.registerKeyboardAction(new
	 * ActionListener() {
	 *
	 * @Override public void actionPerformed(final ActionEvent e) {
	 * CommonDialog.this.dispose(); } }, stroke,
	 * JComponent.WHEN_IN_FOCUSED_WINDOW); return rootPane; }
	 */

}
